package com.irdstudio.apicenter.console.controller.template;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.irdstudio.apicenter.console.service.appframe.AppFrameCertificateService;
import com.irdstudio.apicenter.console.util.MacmsPathUtil;
import com.irdstudio.apicenter.frame.core.jdbc.JdbcBaseDAO;
import com.irdstudio.apicenter.frame.util.BeanUtils;

/**
 * 文件上传的Controller
 * 
 * @author ssg
 */
@Controller
@RequestMapping("uploadTemplateFile")
public class TemplateFileUploadController {
	@Autowired
	private AppFrameCertificateService appFrameCertificateService;

	// private static final String FILE_PATH = "C:/uploaddir";

	@RequestMapping(value = "one", method = RequestMethod.POST)
	public String uploadFile(HttpServletRequest request,
			HttpServletResponse response) throws IOException, SQLException,
			ClassNotFoundException {
		int i = 0;
		String sql = "";
		int flag = -1;
		String templateId = request.getParameter("templateId");
		String fileType = request.getParameter("fileType");
		String FILE_PATH = MacmsPathUtil.mkdirFile("template", templateId);

		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Iterator<String> fileNames = multipartRequest.getFileNames();
		while (fileNames.hasNext()) {
			i++;
			MultipartFile multipartFile = multipartRequest.getFile(fileNames
					.next());
			// 如果使用firebug，或者chrome的开发者工具，可以看到，这个文件上传工具发送了两个文件名
			// 分别是：name="Filedata"; filename="AVScanner.ini"
			// 用这两个文件名获得文件内容都可以，只不过第一个没有后缀，需要自己处理
			// 第二个是原始的文件名，但是这个文件名有可能是上传文件时的全路径
			// 例如 C:/testssh/a.log，如果是全路径的话，也需要处理
			String fileAlias = multipartFile.getName();
			System.out.println("Spring MVC获得的文件名：" + fileAlias);
			// 获得文件原始名称
			String name = multipartFile.getOriginalFilename();// 图片名
			String filePath = FILE_PATH + "/" + name;
			saveFile(filePath, multipartFile.getBytes());

			sql = "insert  into  s_template_file  value('" + templateId + "','"
					+ fileType + "','" + name + "')";
			JdbcBaseDAO baseDao = BeanUtils.getBean(JdbcBaseDAO.class);
			flag = baseDao.insert(sql, null);
			Map<String, String> resultMap = new HashMap<String, String>(5);
			resultMap.put("result", "success");
			resultMap.put("filePath", filePath);
			list.add(resultMap);
		}

		return "success";
		/*
		 * ModelAndView modelAndView = new ModelAndView();
		 * modelAndView.setViewName
		 * ("redirect:/template/createfile?templateId="+templateId); return
		 * modelAndView;
		 */
		// return "success！";
		/*
		 * ModelAndView modelAndView = new ModelAndView();
		 * modelAndView.setViewName
		 * ("redirect:/appFrameStart/appFrameStartDetail1"); return
		 * modelAndView;
		 */

	}

	// 保存文件的方法
	public void saveFile(String filePath, byte[] content) throws IOException {
		BufferedOutputStream bos = null;
		try {
			File file = new File(filePath);
			// 判断文件路径是否存在
			if (!file.getParentFile().exists()) {
				// 文件路径不存在时，创建保存文件所需要的路径
				file.getParentFile().mkdirs();
			}
			// 创建文件（这是个空文件，用来写入上传过来的文件的内容）
			file.createNewFile();
			bos = new BufferedOutputStream(new FileOutputStream(file));
			bos.write(content);
		} catch (FileNotFoundException e) {
			throw new FileNotFoundException("文件不存在。");
		} finally {
			if (null != bos) {
				bos.close();
			}
		}
	}

}
